package uk.gov.swmprobation.cplitebase;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.googlecode.flickrjandroid.Flickr;
import com.googlecode.flickrjandroid.FlickrException;
import com.googlecode.flickrjandroid.photos.Photo;

import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class RecoverProjects extends IntentService {
	
	Bitmap bm;
	
	public RecoverProjects() {
		super("RecoverProjects");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
	    String searchUrl ="http://cpvisibility.org/solr/core1/select?q=*%3A*&fq=phone%3A"+deviceId+"&rows=30&wt=json";
	    HttpGet httpGet = new HttpGet(searchUrl);
	    try {
	      HttpResponse response = client.execute(httpGet);
	      StatusLine statusLine = response.getStatusLine();
	      int statusCode = statusLine.getStatusCode();
	      if (statusCode == 200) {
	        HttpEntity entity = response.getEntity();
	        InputStream content = entity.getContent();
	        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
	        String line;
	        while ((line = reader.readLine()) != null) {
	          builder.append(line);
	        }
	      }
	    } catch (ClientProtocolException e) {
	      e.printStackTrace();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	    
	    String responce = builder.toString();
	    JSONObject jObject;
	    JSONArray projectsArray;
	    
	    try {
			jObject = new JSONObject(responce);
			projectsArray = jObject.getJSONObject("response").getJSONArray("docs");
			if(projectsArray.length()==0){
				return;
			}
			DatabaseHandler.deleteProjectMine();
			int n=projectsArray.length();
			for (int i = 0; i < n; i++){
				
				String location = projectsArray.getJSONObject(i).getString("location");
				String[] splitLocation = location.split(",");
				double lat = Double.parseDouble(splitLocation[0]);
				double lng = Double.parseDouble(splitLocation[1]);				
				
				Project project = new Project();
				project.setId(0);
				project.setLat(lat);
				project.setLng(lng);
				project.setProjectComment(projectsArray.getJSONObject(i).getString("comment"));
				project.setProjectId(projectsArray.getJSONObject(i).getInt("id"));
				project.setProjectName(projectsArray.getJSONObject(i).getString("title"));
				project.setProjectType(Project.TYPE_MINE);
				project.setTrust(projectsArray.getJSONObject(i).getString("trust"));
				project.setUpdated(Project.SENT_FINISHED);
				project.setImagePath(projectsArray.getJSONObject(i).getString("photo_id"));
				project.save();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    Log.e("Recover",responce);
	    
	}
}